package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author 寒士obj
 * @date 2025/07/06 11:29
 **/
public class SimpleRedisLock implements ILock{

    /**
     * 在多线程+分布式环境下，即使同一个用户的请求针对相同的 key，
     * 通过给锁的 value 加上唯一标识，并用「比较 value」判断解锁权限，能防止误释放、保证锁的正确性与系统并发安全。
     */

    // 业务名称
    private String name;
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private StringRedisTemplate stringRedisTemplate;
    private static final DefaultRedisScript<Long> SCRIPT;
    static {
        SCRIPT = new DefaultRedisScript<>();
        SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        String key = KEY_PREFIX + name;
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(key, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock() {
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 调用lua脚本，保证原子性
        stringRedisTemplate.execute(SCRIPT, Collections.singletonList(KEY_PREFIX + name), threadId);
    }

    /*@Override
    public void unLock() {
        // 获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 判断锁标识
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);

        *//**
         * 注意：这里判断锁和释放锁是两个步骤并没有实现原子操作，要用lua脚本实现
         *//*

        // 判断锁是否是自己的
        if (threadId.equals(id)) {
            // 释放锁
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }
    }*/
}
